# -*- encoding: utf-8 -*-
from django.views.generic.list_detail import object_list
from django.contrib.auth.decorators import permission_required
from django.shortcuts import render_to_response
from django.http import HttpResponseRedirect, Http404
from django.shortcuts import get_object_or_404
from django.utils.translation import ugettext as _

from django.contrib.auth.models import User
from wagglyblog.models import Post, Category
from wagglyblog.forms import SimplePostForm


def author_list(request):
    # clumsy way of getting authors list
    authors = Post.objects.values('author').distinct()
    authors_ids = [int(x['author']) for x in authors]
    if len(authors_ids) == 1:
        author_ids = "(%s)" % authors_ids[0]
    else:
        author_ids = str(tuple(authors_ids))
    authors = User.objects.extra(where=['id IN %s' % author_ids])
    return render_to_response('wagglyblog/author_list.html', {'object_list': authors})

def author(request, username):
    # TODO: can be done with plain generic views since some revision ago
    queryset = Post.published.filter(author__username__exact=username)
    return object_list(request, queryset, extra_context={'author': username})

def category_postlist(request, slug):
    if slug == "none":
        categories = [_("Uncategorized")]
        posts = Post.published.filter(categories__slug__isnull=True)
    else:
        # if the slug has a plus in it, then split it
        slugs = slug.split('+')
        categories = Category.objects.filter(slug__in=slugs)
        if len(categories) < len(slugs):
          raise Http404
        posts = Post.published.filter(categories__in=categories)
    return render_to_response('wagglyblog/category_postlist.html',
        {'categories': categories, 'post_list': posts})

@permission_required('wagglyblog.add_post')
def add(request):
    if request.method == 'POST':
        form = SimplePostForm(request.POST)

        if form.is_valid():
            new_data = form.cleaned_data.copy()

            # add required fields
            new_data['author'] = request.user
            new_data['is_published'] = True

            # Post is valid and the required data automatically added
            # so we can save it and redirect to its absolute url
            # WARNING: could Post instanciation possibly fail?
            new_post = Post(**new_data)
            new_post.save()

            return HttpResponseRedirect(new_post.get_absolute_url())
    else:
        form = SimplePostForm()
    return render_to_response('wagglyblog/create_form.html', {'form': form})
